import { message, Form } from 'antd';
import { createContainer } from 'unstated-next';
import { useAntdTable, useRequest } from 'ahooks';

import {
  deleteRoleInfo,
  postRoleList,
  setRoleStatus,
} from '@/services/systemManagement/role';

import useEdit from './useEdit';


export default createContainer(() => {
  // 搜索表单
  const [form] = Form.useForm();
  const editHooks = useEdit();

  // 角色列表
  const tableHooks = useAntdTable(
    async ({ current, pageSize }, params) => {
      const res = await postRoleList({
        current,
        pageSize,
        ...params,
      });
      return {
        list: res?.data || [],
        total: res?.total || 0,
      };
    },
    {
      form,
    },
  );

  // 设置角色状态
  const updateRoleStatus = useRequest(
    async (query: { id: number, status: number }) => {
      const res = await setRoleStatus(query);
      if (res.success) {
        message.success('操作成功！');
        tableHooks.refresh();
      }
    },
    {
      manual: true,
    },
  );
  //删除角色
  const deleteRole = useRequest(
    async (id: number) => {
      const res = await deleteRoleInfo({ id });
      if (res?.success) {
        message.success('删除成功');
        tableHooks.refresh();
      }
    },
    {
      manual: true,
    },
  );



  return {
    tableHooks,
    updateRoleStatus,
    editHooks,
    deleteRole,
    form,
  };
});
